package com.iot.service.mqtt.codec.encoder;

import com.iot.service.mqtt.model.fix.TlMqttFixedHead;
import com.iot.service.mqtt.model.response.TlMqttConnack;
import com.iot.service.mqtt.model.variable.TlMqttConnackVariableHead;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.handler.codec.mqtt.MqttMessageType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @Author: hszhou
 * @Date: 2024/11/30 15:35
 * @Description: 必须描述类做什么事情, 实现什么功能
 */
@ChannelHandler.Sharable
@Component
public class TlMqttConnackEncoder extends MessageToByteEncoder<TlMqttConnack> {

    private static final Logger logger = LoggerFactory.getLogger(TlMqttConnackEncoder.class);

    @Override
    protected void encode(ChannelHandlerContext ctx, TlMqttConnack res, ByteBuf out) throws Exception {
        logger.debug("in【CONNACK】 encode");
        TlMqttFixedHead fixedHead = res.getFixedHead();
        TlMqttConnackVariableHead variableHead = res.getVariableHead();
        int currentSession = variableHead.getCurrentSession();
        int code = variableHead.getCode();
        MqttMessageType messageType = fixedHead.getMessageType();
        //消息类型
        out.writeByte(messageType.value() << 4);
        //剩余长度
        out.writeByte(Short.BYTES);
        out.writeByte(currentSession);
        out.writeByte(code);
    }

}
